<template>
    <div>
        <div>
            <Toolbar
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                mode="simple"
            />
        </div>
        <Editor
            style="height: 500px; overflow-y: hidden;border: 1px solid #ccc;"
            v-model="$value"
            :defaultConfig="editorConfig"
            mode="simple"
            @onCreated="handleCreated"
            @onChange="handleChange"
        />
    </div>
</template>
<script lang="ts" setup>
    import '@wangeditor/editor/dist/css/style.css' // 引入 css
    import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { onBeforeUnmount, ref, shallowRef } from 'vue';

    const props = defineProps<{
        modelValue:string;
        uploadApi : (file:File) => Promise<any>
    }>()

    const emit = defineEmits<{
        (e : 'update:modelValue', value:string) : void
    }>()

    const $value = ref<string>('')
    
    if(props.modelValue) {
        $value.value = props.modelValue
    }

    function handleChange() {
        emit('update:modelValue', $value.value)
    }


    const editorRef = shallowRef()

    const toolbarConfig = {}
    const editorConfig = {
        MENU_CONF : {
            uploadImage : {
                async customUpload(file, insertFn) {
                    const res = await props.uploadApi(file)
                    // file 即选中的文件
                    // 自己实现上传，并得到图片 url alt href
                    // 最后插入图片
                    if(res.success) {
                        insertFn(import.meta.env.B_NET_STATIC_URL + res.data, '', '')
                    }
                    
                }
            }
        },

        placeholder: '请输入内容...'
    }


    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
        const editor = editorRef.value
        if (editor == null) return
        editor.destroy()
    })

    const handleCreated = (editor) => {
      editorRef.value = editor // 记录 editor 实例，重要！
    }
</script>